import {
  ADD_PRODUCT,
  REMOVE_PRODUCT,
  CLEAR_PRODUCTS
} from '../mutationTypes'

// 购物车数据结构
// shopcarts:{
//   'restaurant_id':{
//     'category_id':{
//       'food_id':{
//       }
//     }
//   }
// }
const defaultState = {
  // 购物车记录
  shopcarts:{}, 
}


const getters = {
}

const mutations = {
  // 添加商品
  [ADD_PRODUCT](state,{restaurant_id,category_id, product}){
    const {food_id} = product
    const shopcarts = state.shopcarts
    const shopcart = shopcarts[restaurant_id] || {}
    const category = shopcart[category_id] || {}

    category[food_id] = product
    shopcart[category_id] = category
    shopcarts[restaurant_id] = shopcart
    state.shopcarts = {...shopcarts} //让shopcarts发生变化，这样在mapState中才可以响应
  },

  // 删除商品
  [REMOVE_PRODUCT](state, {restaurant_id,category_id, product}){
    const {food_id} = product
    const shopcarts = state.shopcarts
    const shopcart = shopcarts[restaurant_id]
        //如果shopcart==undefined则返回shopcart;shopcart存在则返回shopcart[category_id]
    const category = shopcart && shopcart[category_id] 
    if(category && category[food_id]){
      if(product.quantity === 0){
        delete category[food_id]
      }else{
        category[food_id] = product
      }
    }
    state.shopcarts = {...shopcarts}
  },
  // 清空商品
  [CLEAR_PRODUCTS](state, {restaurant_id}){
    state.shopcarts[restaurant_id] = {}
  }
}

const actions = {
  // 添加到购物车
  [ADD_PRODUCT]({commit}, {
    restaurant_id,
    category_id,
    geohash,
    // 购物车数据
    item_id,    //同一规格id
    food_id,    //食品id,
    name,       //食品名称,
    packing_fee,//打包费,
    price,    //价格,
    sku_id,   //规格id,
    specs,    // 规格,
    stock,     //存量,
    quantity //数量,
  }){
    // 异步添加商品至购物车

    commit(ADD_PRODUCT, {
      restaurant_id,
      category_id,
      product:{
        item_id,   
        food_id,    
        name,
        packing_fee,
        price,
        sku_id,
        specs,
        stock,
        quantity
      }
    })
  },
  // 移除购物车
  [REMOVE_PRODUCT]({commit}, {
    restaurant_id,
    category_id,
    geohash,
    // 购物车数据
    item_id,    //同一规格id
    food_id,    //食品id,
    name,       //食品名称,
    packing_fee,//打包费,
    price,    //价格,
    sku_id,   //规格id,
    specs,    // 规格,
    stock,     //存量,
    quantity //数量,
  }){
    // 异步移出购物车
    commit(REMOVE_PRODUCT, {
      restaurant_id,
      category_id,
      product:{
        item_id,   
        food_id,    
        name,
        packing_fee,
        price,
        sku_id,
        specs,
        stock,
        quantity
      }
    })
  },
  // 清空购物车
  [CLEAR_PRODUCTS]({commit}, {restaurant_id}){
    commit(CLEAR_PRODUCTS, {restaurant_id})
  }
}

// 导出模块
export default {
  namespaced: true, //一定要设为true，否则会找不到模块
  state: Object.assign({}, defaultState),
  getters,
  mutations,
  actions
}
